package main

import (
	"bufio"
	"fmt"
	"os"
	"os/exec"
	"strings"
)

func main() {
	filePath := "D:\\code_zch\\code_script_bat_sh\\git-manage\\my-repo-2.txt"
	checkRepositories(filePath)
}

func checkRepositories(filePath string) {
	file, err := os.Open(filePath)
	if err != nil {
		fmt.Println("Error opening the file:", err)
		return
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			fmt.Println("Error closing the file:", err)
		}
	}(file)

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		repoPath := scanner.Text()
		// Remove any leading/trailing whitespaces.
		repoPath = strings.TrimSpace(repoPath)
		if repoPath == "" {
			continue // Skip empty lines
		}

		fmt.Println("Checking repository:", repoPath)
		err := os.Chdir(repoPath)
		if err != nil {
			fmt.Println("Error changing repo:", err)
			return
		}
		output, err := exec.Command("git", "status", "--porcelain").CombinedOutput()
		if err != nil {
			fmt.Println("Error checking the repository:", err)
			continue
		}

		status := string(output)
		if strings.TrimSpace(status) == "" {
			fmt.Println("The working tree is clean. Nothing to commit.")
		} else {
			fmt.Println("Changes detected. Status:\n", status)
			// Example: Git pull to get the latest changes
			//if _, err := exec.Command("git", "pull").Output(); err != nil {
			//	fmt.Println("Error pulling the repository:", err)
			//} else {
			//	fmt.Println("Successfully pulled the repository.")
			//}

			// Additional Git commands can be added here, such as git add, git commit, etc.
		}
	}

	if err := scanner.Err(); err != nil {
		fmt.Println("Error reading the file:", err)
	}
}
